package com.cn.tous.common.security.aspect;

/**
 * @author mengwei
 * @description PermissionAspect
 * @createDate 2025/7/26 12:34
 */

import com.cn.tous.common.security.annotation.RequiresPermission;
import com.cn.tous.common.security.utils.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 权限注解切面，实现方法级别的权限控制
 * @author 73578
 */
@Aspect
@Component
public class PermissionAspect {

    /**
     * 在方法执行前检查权限
     */
    @Before("@annotation(com.cn.tous.common.security.annotation.RequiresPermission)")
    public void checkPermission(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RequiresPermission annotation = method.getAnnotation(RequiresPermission.class);

        String[] permissions = annotation.value();
        boolean requireAll = annotation.requireAll();

        // 检查权限
        if (requireAll) {
            // 需要所有权限
            for (String permission : permissions) {
                if (!SecurityUtils.hasAuthority(permission)) {
                    throw new AccessDeniedException("没有权限: " + permission);
                }
            }
        } else {
            // 需要至少一个权限
            boolean hasAnyPermission = false;
            for (String permission : permissions) {
                if (SecurityUtils.hasAuthority(permission)) {
                    hasAnyPermission = true;
                    break;
                }
            }
            if (!hasAnyPermission) {
                throw new AccessDeniedException("没有所需的任何权限");
            }
        }
    }
}
